<?php

namespace App\Http\Middleware;

use App\Exceptions\lin\LinException;
use Closure;

class Cors
{
    public function handle($request, Closure $next)
    {
        if ($request->route('id') && (int)$request->route('id') < 1) {
            throw new LinException(['msg' => '路由参数错误', 'code' => 10030]);
        }
        $cors = config('cors');
        $origin = $request->server('HTTP_ORIGIN') ?? '';
        $response = $next($request);
        // 判断请求头中是否包含ORIGIN字段
        /*if (!in_array($origin, $cors['allowed_origins'])) {
            throw new LinException(10012);
        }*/
        //设置响应头信息
        $response->header('Access-Control-Allow-Origin', $origin);
        $response->header('Access-Control-Allow-Headers', $cors['allowed_headers']);
        $response->header('Access-Control-Allow-Methods', $cors['allowed_methods']);
        $response->header('Access-Control-Allow-Credentials', $cors['supports_credentials']);
        $response->header('Access-Control-Max-Age', $cors['max_age']);
        $response->header('Allow', $cors['allowed_methods']);
        /*$response->header('Access-Control-Expose-Headers', '*');*/
        return $response;
    }
}
